#include <Windows.h>
#include <gl/freeglut.h>
#include <math.h>

int ww, hh;			// for display window width and height
int line[4], k = 0; // for line's endpoint coordinates and line number

void init(void);
void reshape(int w, int h);
void myMouse(int button, int state, int x, int y);
void myMotion(int x, int y);
void display(void);
void line_DDA(int x0, int y0, int xn, int yn);

int main(int argc, char **argv)
{
	glutInit(&argc, argv);
	glutInitWindowSize(800, 600);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutCreateWindow("Draw Lines");
	init();
	glutDisplayFunc(display);
	glutMouseFunc(myMouse);
	glutMotionFunc(myMotion);
	glutReshapeFunc(reshape);
	glutMainLoop();
	return 0;
}
// Event drinving ; Message sending

void init(void)
{
	// 设定帧缓存的初始值，glClear();
	glClearColor(1.0, 1.0, 1.0, 0.0);
}

// 渲染绘制回调函数--------------------------------------------------------------------------
void display(void)
{
	glClear(GL_COLOR_BUFFER_BIT);

	line_DDA(line[0], line[1], line[2], line[3]);
}

// 窗口大小改变回调函数-----------------------------------------------
void reshape(int w, int h)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glViewport(0, 0, w, h);
	gluOrtho2D(0, w, 0, h);
	ww = w;
	hh = h;
}

void myMouse(int button, int state, int x, int y)
{
	if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
	{
		line[0] = x;
		line[1] = hh - y;//操作系统的坐标系和OpenGL的坐标系在Y方向相反
	}

	if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
	{
		line[2] = x;
		line[3] = hh - y;
		glutPostRedisplay();
	}
}

void myMotion(int x, int y)
{
	// get the line's motion point
	// 获取鼠标左键按下时（持续按着左键），移动鼠标得到点
	line[2] = x;
	line[3] = hh - y;
	glutPostRedisplay();
}

// DDA
void line_DDA(int x0, int y0, int xn, int yn)
{
	glColor3f(1.0, 0, 0);
	glPointSize(2);
	int dx = xn - x0, dy = yn - y0;
	float xIncrement, yIncrement, steps, x = x0, y = y0;
	if (abs(dx) > abs(dy))
		steps = abs(dx);
	else
		steps = abs(dy);
	xIncrement = (float)(dx) / steps;
	yIncrement = (float)(dy) / steps;

	for (int i = 0; i < steps; i++)
	{
		glBegin(GL_POINTS);
		glVertex2f(int(x), int(y));
		glEnd();
		glFlush();
		x += xIncrement;
		y += yIncrement;
	}
}